package edu.gznu.ics.fast.common;


import org.codehaus.jettison.json.JSONException;
import org.codehaus.jettison.json.JSONObject;

import java.io.BufferedReader;
import java.io.DataOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.io.OutputStream;
import java.io.UnsupportedEncodingException;
import java.net.HttpURLConnection;
import java.net.MalformedURLException;
import java.net.ProtocolException;
import java.net.URL;


/**
 * Created by fei-zyx on 2017/4/25.
 */

public class HttpHelper {
    public static final String ADD_URL = "http://localhost/getwaterqcAlldata";

    /**
     * 从指定的URL中获取数组
     *
     * @param urlPath
     * @return
     * @throws Exception
     */
    public static String httpUrlPostHelper(String urlPath,/*JSONObject*/ String postPara) throws Exception {
        URL url = null;
        try {
            url = new URL(urlPath);
            HttpURLConnection httpURLConnection = (HttpURLConnection) url.openConnection();
            httpURLConnection.setRequestMethod("POST");// 提交模式
            httpURLConnection = (HttpURLConnection) url.openConnection();
            // 设置文件长度
            //  httpURLConnection.setRequestProperty("Content-Length", String.valueOf((postPara.toString()).getBytes().length));


            httpURLConnection.setRequestProperty("Content-Type", "application/json; charset=utf-8");
            httpURLConnection.setUseCaches(false);

            // 设置维持长连接
            httpURLConnection.setRequestProperty("Connection", "Keep-Alive");
            httpURLConnection.setConnectTimeout(20000);
            httpURLConnection.setReadTimeout(300000);
            httpURLConnection.setRequestProperty("Charset", "UTF-8");


            //
            // conn.setConnectTimeout(10000);//连接超时 单位毫秒
            // conn.setReadTimeout(2000);//读取超时 单位毫秒
            // 发送POST请求必须设置如下两行
            httpURLConnection.setDoOutput(true);
            httpURLConnection.setDoInput(true);
            // 获取URLConnection对象对应的输出流
            OutputStream out = httpURLConnection.getOutputStream();
            // 发送请求参数
            out.write((postPara/*.toString()*/).getBytes());//post的参数 xx=xx&yy=yy
            // flush输出流的缓冲
            out.flush();
            //开始获取数据

            if (httpURLConnection.getResponseCode() == 200) {
                System.out.println("连接成功");
                // 请求返回的数据
                InputStream in = httpURLConnection.getInputStream();
                String a = null;
                try {
                    byte[] arr = new byte[in.available()];
                    in.read(arr);
                    // 转成字符串
                    return new String(arr, "utf-8");
                    // System.out.println(a);
                } catch (Exception e1) {
                    // TODO Auto-generated catch block
                    e1.printStackTrace();
                }
            } else {
                System.out.println("no++");
            }
        } catch (Exception e) {
            e.printStackTrace();
        }

//            BufferedInputStream bis = new BufferedInputStream(httpURLConnection.getInputStream());
//            ByteArrayOutputStream bos = new ByteArrayOutputStream();
//            int len;
//            byte[] arr = new byte[1024];
//            while((len=bis.read(arr))!= -1){
//                bos.write(arr,0,len);
//                bos.flush();
//            }
//            bos.close();
//            return bos.toString("utf-8");
//        } catch (Exception e) {
//            e.printStackTrace();
//        }
        return null;
    }

    public static void main(String args[]) throws Exception {
        //JSONObject jsonObject = new JSONObject();
        //  obj.put("date","2017-03-09");


        //   System.out.println(obj);

//        String a = null;
//        try {
//            a = httpUrlPostHelper("http://localhost/getwaterqcdataBydateAndSection", "date=2017-03-09&sectionName=草海BJS-40");
//        } catch (Exception e) {
//            e.printStackTrace();
//        }
//        System.out.print(a);
//        JSONObject lists = (JSONObject) JsonHepler.toObject(a, WaterQCPO[].class);
//        JSONArray listArray = lists.getJSONArray("list");
//        int as = 0;
        // List<Map<String, String>> list2 = (List<Map<String, String>>) listArray
        appadd();

    }


    public static void appadd() {
        try {
            //创建连接
            URL url = new URL(ADD_URL);
            HttpURLConnection connection = (HttpURLConnection) url.openConnection();
            connection.setDoOutput(true);
            connection.setDoInput(true);
            connection.setRequestMethod("POST");
            connection.setUseCaches(false);
            connection.setInstanceFollowRedirects(true);
            connection.setRequestProperty("Content-Type",
                    "application/x-www-form-urlencoded");

            connection.connect();

            //POST请求
            DataOutputStream out = new DataOutputStream(connection.getOutputStream());
            JSONObject obj = new JSONObject();
            obj.accumulate("date", "2017-03-09");
//            obj.put("app_ip", "10.21.243.234");
//            obj.put("app_port", 8080);
//            obj.put("app_type", "001");
//            obj.put("app_area", "asd");

            out.writeBytes(obj.toString());
            out.flush();
            out.close();

            //读取响应
            BufferedReader reader = new BufferedReader(new InputStreamReader(connection.getInputStream()));
            String lines;
            StringBuffer sb = new StringBuffer("");
            while ((lines = reader.readLine()) != null) {
                lines = new String(lines.getBytes(), "utf-8");
                sb.append(lines);
            }

            String x = sb.toString();
            System.out.println(x);
            reader.close();
            // 断开连接
            connection.disconnect();
        } catch (MalformedURLException e) {
            // TODO Auto-generated catch block
            e.printStackTrace();
        } catch (UnsupportedEncodingException e) {
            // TODO Auto-generated catch block
            e.printStackTrace();
        } catch (IOException e) {
            // TODO Auto-generated catch block
            e.printStackTrace();
        } catch (JSONException e) {
            e.printStackTrace();
        }

    }


}
